﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Jumpton.SFA.Server.BusinessRule;
using Jumpton.SFA.Server.Entity;
using Jumpton.SFA.Server.BusinessRule.MasterData;
using Jumpton.SFA.Server.BusinessRule.System;
using Jumpton.Persistent;
using Jumpton.Data;

public partial class OrderManagement_Order_Report_Print : PageBase
{

    /// <summary>
    /// 右边的页码
    /// </summary>
    Hashtable htRight;
    /// <summary>
    /// 左边的页码
    /// </summary>
    Hashtable htLeft;
    /// <summary>
    /// 每页显示的行数
    /// </summary>
    private const int pageSize = 25;

    protected void Page_Load(object sender, EventArgs e)
    {
        //if (txtHidOrg.Value == "")
        //{
        //    txtHidOrg.Value = OrgHidValue;
        //    txtOrg.Text = OrgShowValue;
        //    OrgHelper.BindUsersDDLEX(MyStateManager.DomainID, txtHidOrg.Value, ddlMobileUser);
        //    OrgHelper.BindChiansDDL(MyStateManager.DomainID, txtHidOrg.Value, ddlChains);
        //}

        if (!IsPostBack)
        {
            DataBind();
            if (txtHidOrg.Value == "")
            {
                this.txtHidOrg.Value = OrgHidValue;
                this.txtOrg.Text = OrgShowValue;
                OrgHelper.BindChiansDDL(MyStateManager.DomainID, this.txtHidOrg.Value, this.ddlChains);
                var data = new OrgainzationManager().SearchOrgTree(MyStateManager.DomainID, MyStateManager.OrgID, null);
                if (data.Rows.Count != 1)
                {
                    OrgHelper.BindUsersDDL(MyStateManager.DomainID, this.txtHidOrg.Value, this.ddlMobileUser);
                }
                else
                {
                    Person person = new PersonManager().Load(MyStateManager.PersonID);
                    ddlMobileUser.Items.Add(new ListItem(person.Name, MyStateManager.UserID.ToString()));
                }

            }
            txtDate.Value = DateTime.Now.ToShortDateString();
            InitForm();
            
        }
    }
    /// <summary>
    /// 初始化部分文本
    /// </summary>
    protected void InitForm()
    {
        USER_CHAINS userChains = new UserManager().LoadChainsByUser(this.MyStateManager.UserID);
        var data = new OrgainzationManager().SearchOrgTree(MyStateManager.DomainID, MyStateManager.OrgID, null);
        //经销商用户
        if (userChains != null)
        {
            txtOrg.Text = new OrgainzationManager().Load(MyStateManager.OrgID).NAME;
            txtHidOrg.Value = "'" + MyStateManager.OrgID + "'";
            OrgHelper.BindChiansDDL(MyStateManager.DomainID, txtHidOrg.Value, ddlChains);
            ddlChains.SelectedValue = userChains.CHAINSID.ToString();
            ddlChains.Enabled = false;
           
           
        }
       

    }

    protected void SelectPersons(object sender, EventArgs e)
    {
        if (ddlMobileUser.SelectedIndex == 0)
        {
            Bindchains();
        }
        else
        {
             ddlChains.Items.Clear();
            //获取当前业务员ID
         
             DataTable dt = new ChainManager().GetChainsByUser(decimal.Parse(ddlMobileUser.SelectedValue));
              foreach (DataRow row in dt.Rows)
              {
                   this.ddlChains.Items.Add(new ListItem(row["DESCRIPTION"].ToString(), row["ID"].ToString()));
              }
           
             ddlChains.Items.Insert(0, new ListItem("--所有--", ""));
        
        }

    }

    private void Bindchains()
    {
         ddlChains.Items.Clear();
      
        DataTable dt = new ChainManager().GetCourseTable(MyStateManager.DomainID, txtHidOrg.Value);
          foreach (DataRow row in dt.Rows)
          {
               this.ddlChains.Items.Add(new ListItem(row["DESCRIPTION"].ToString(), row["ID"].ToString()));
          }
       
          ddlChains.Items.Insert(0, new ListItem("--所有--", ""));
        
    }

    protected void txtOrg_TextChanged(object sender, EventArgs e)
    {
        Bindchains();
        ddlMobileUser.Items.Clear();
        

        //判断当前的人所在的部门是不是最小的一级org
        var data = new OrgainzationManager().SearchOrgTree(MyStateManager.DomainID, MyStateManager.OrgID, null);
        if (data.Rows.Count != 1)
        {
            OrgHelper.BindUsersDDL(MyStateManager.DomainID, this.txtHidOrg.Value, this.ddlMobileUser);
        }
        else
        {
            Person person = new PersonManager().Load(MyStateManager.PersonID);
            ddlMobileUser.Items.Add(new ListItem(person.Name, MyStateManager.UserID.ToString()));
            //查找该用户关联的经销商

        }
      

    }

    /// <summary>
    /// 数据绑定
    /// </summary>
    protected void BindGrid()
    {
        this.panelx.Controls.Clear();

        DateTime date = DateTime.Parse(txtDate.Value);

        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        sb.AppendFormat(" AND OH.DOMAIN_ID = {0}", MyStateManager.DomainID);

        sb.AppendFormat(" AND dbo.[GetDateTimeByBigint](OH.ORDER_DATE) >= '{0}' AND dbo.[GetDateTimeByBigint](OH.ORDER_DATE) <'{1}'", date, date.AddDays(1).AddMinutes(-1));

        if (string.IsNullOrEmpty(txtHidOrg.Value))
        {
            return;
        }

        sb.AppendFormat(" AND PERSONS.ORG_ID IN ({0})", txtHidOrg.Value);

        if (!string.IsNullOrEmpty(ddlMobileUser.SelectedValue))
        {
            sb.AppendFormat(" AND OH.PERSON_ID IN (SELECT PERSON_ID FROM USERS WHERE USERS.ID='{0}' )", ddlMobileUser.SelectedValue);
        }

        if (!string.IsNullOrEmpty(ddlChains.SelectedValue))
        {
            sb.AppendFormat(" AND CH.ID = {0}", ddlChains.SelectedValue);
        }

        DataSet ds = OrderHeaderManager.SearchSupplyReport(sb.ToString());

        if (ds != null && ds.Tables.Count > 0)
        {
            CalcPageNumber(ds.Tables[0]);
            FillPanel(ds.Tables[0]);
        }

    }

    protected void CalcPageNumber(DataTable dt)
    {
        htRight = new Hashtable();
        htLeft = new Hashtable();

        string lastChainName = string.Empty;
        string lastUSERNAME = string.Empty;
        string lastSupplyName = string.Empty;

        int rowCount = dt.Rows.Count;
        int j = 1;


        //遍历每行的页码，统计两个页码之间出现变化所需要的行数。
        //Table是按照订单排序的，例如订单号是333到订单号是555之间有12个333的订单号，
        //那么变量J就为12，然后通过对J的计算，将正确的页码插入两个Hastable.
        for (int i = 0; i < rowCount; )
        {
            lastChainName = dt.Rows[i]["CHAIN_NAME"].ToString();
            lastUSERNAME = dt.Rows[i]["USERNAME"].ToString();
            lastSupplyName = dt.Rows[i]["SUPPLY_NAME"].ToString();

            j = 1;

            while (i < rowCount && lastChainName == dt.Rows[i]["CHAIN_NAME"].ToString() &&
                lastUSERNAME == dt.Rows[i]["USERNAME"].ToString() && lastSupplyName == dt.Rows[i]["SUPPLY_NAME"].ToString())
            {
                j++;
                i++;
            }

            //回到最后一个匹配的J计数
            j--;

            //键记行号，值记总页数

            if (j / pageSize > 0)
            {
                int k = 1;
                for (; k < j / pageSize + 1; k++)
                {
                    //键-插入值， 值如果能被页码除尽，就是正好多少页，就不用加1。否则需要加1
                    htRight.Add(i - j + k * pageSize, (j % pageSize == 0) ? j / pageSize : j / pageSize + 1);
                    //K为页码(例:2/3)的左边部分(2)
                    htLeft.Add(i - j + k * pageSize, k);
                }

                //如果计算出的页码值不能除尽的，就再添加最后一页的值
                if (j % pageSize != 0)
                {
                    htRight.Add(i, j / pageSize + 1);
                    htLeft.Add(i, k);
                }

            }
            else
            {
                htRight.Add(i, 1);
                htLeft.Add(i, 1);
            }


        }
    }

    protected void FillPanel(DataTable dt)
    {
        int rowCount = dt.Rows.Count;
        int leftPageIndex = 1;
        int rightPageIndex = 1;

        if (dt.Rows.Count <= 0)
        {
            return;
        }

        string lastChainName = string.Empty;
        string lastUSERNAME = string.Empty;
        string lastSupplyName = string.Empty;

        for (int i = 0; i < rowCount; )
        {
            lastChainName = dt.Rows[i]["CHAIN_NAME"].ToString();
            lastUSERNAME = dt.Rows[i]["USERNAME"].ToString();
            lastSupplyName = dt.Rows[i]["SUPPLY_NAME"].ToString();

            UserControl_PrintTempleteForOrderReport PrintTemp = (UserControl_PrintTempleteForOrderReport)Page.LoadControl("../UserControl/PrintTempleteForOrderReport.ascx");

            //更新label的值
            PrintTemp.OrgName = dt.Rows[i]["ORG_NAME"].ToString();
            PrintTemp.ChainName = dt.Rows[i]["CHAIN_NAME"].ToString();
            PrintTemp.SupplyName = dt.Rows[i]["SUPPLY_NAME"].ToString();
            PrintTemp.UserNameAndTel = dt.Rows[i]["NAMEPHONE"].ToString();
            PrintTemp.OrderDate = ((DateTime)dt.Rows[i]["ORDER_DATE"]).ToShortDateString();
            PrintTemp.DateTime = DateTime.Now.ToString();

            DataTable dtPrint = dt.Clone();

            //计算填充了多少行
            int fillRow = 0;

            while (i < rowCount &&
                    lastChainName == dt.Rows[i]["CHAIN_NAME"].ToString() &&
                    lastUSERNAME == dt.Rows[i]["USERNAME"].ToString() &&
                    lastSupplyName == dt.Rows[i]["SUPPLY_NAME"].ToString() && fillRow < pageSize
                                    )
            {
                dtPrint.ImportRow(dt.Rows[i]);
                fillRow++;
                i++;
            }

            //填充空行
            for (int emptyindex = dtPrint.Rows.Count; emptyindex < pageSize; emptyindex++)
            {
                dtPrint.Rows.Add("");
            }

            PrintTemp.GridViewTable.DataSource = dtPrint;
            PrintTemp.DataBind();
            PrintTemp.MadePrinter(i.ToString());


            //判断页码值
            if (htRight.ContainsKey(i))
            {
                leftPageIndex = (int)htLeft[i];
                rightPageIndex = (int)htRight[i];
            }
            else
            {
                leftPageIndex = (int)htLeft[i];
            }

            //添加页码
            PrintTemp.PagerText = leftPageIndex.ToString() + "/" + rightPageIndex.ToString();

            this.panelx.Controls.Add(PrintTemp);
        }

        PrintArea.Visible = true;
    }



    protected void btnSearch_Click(object sender, EventArgs e)
    {
        BindGrid();
    }

    //导出所有表格EXCEL
    protected void btnExport_Click(object sender, EventArgs e)
    {
        // this.Response.Redirect("..\\ExportExcel\\ExportExcel.aspx?Table=OrderReport&Org="+ddlOrg.SelectedValue+"&Chains="+ddlChains.SelectedValue+"&User="+ddlUser.SelectedValue+"&VisitDate="+txtDate.Value);
        BindGrid();

        System.IO.StringWriter tw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
        foreach (Control cr in panelx.Controls)
        {
            cr.RenderControl(hw);
        }
        string attachment = "attachment; filename=" + DateTime.Now.ToShortDateString() + ".xls";
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AddHeader("content-disposition", attachment);
        Response.Charset = "UTF-8";
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");

        Response.Write(tw.ToString());
        Response.End();
    }
}
